import bcrypt from 'bcrypt';
import chalk from 'chalk';
import prisma from './prisma';

/**
 * 执行数据库种子脚本：初始化默认数据
 */
export async function initializeDatabaseSeed() {
  try {
    // 一、初始化文件存储系统类型枚举数据
    const defaultStorageSystemTypeEnum = await prisma.storageSystemTypeEnum.findFirst({
      where: {
        name: 'local',
      },
    });
    if (!defaultStorageSystemTypeEnum) {
      await prisma.storageSystemTypeEnum.createMany({
        data: [
          {
            name: 'local',
            description: '本地存储服务：私有的文件存储系统',
          },
          {
            name: 'oss',
            description: '公共云服务：阿里云对象存储',
          },
          {
            name: 'obs',
            description: '公共云服务：华为云对象存储',
          },
          {
            name: 'cos',
            description: '公共云服务：腾讯云对象存储',
          },
          {
            name: 's3',
            description: '公共云服务：亚马逊对象存储',
          },
          {
            name: 'kodo',
            description: '公共云服务：七牛云对象存储',
          },
        ],
      });
      console.log('', chalk.green.bold('✓'), 'Initialize data table: StorageSystemTypeEnum');
    }
    // 二、初始化 local 存储类型 对应的配置字段
    const defaultLocalConfigField = await prisma.storageSystemConfigField.findFirst({
      where: {
        storageSystemType: {
          name: 'local',
        },
      },
      include: {
        storageSystemType: true,
      },
    });
    if (!defaultLocalConfigField) {
      const localTypeEnum = await prisma.storageSystemTypeEnum.findFirst({
        where: {
          name: 'local',
        },
      });
      if (!localTypeEnum) {
        throw new Error('请先初始化数据表 StorageSystemTypeEnum local 类型');
      }
      await prisma.storageSystemConfigField.createMany({
        data: [
          {
            name: 'basePath',
            description: '文件存储地址',
            type: 'string',
            isRequired: true,
            storageSystemTypeId: localTypeEnum.id,
          },
          {
            name: 'cachePath',
            description: '文件缓存地址',
            type: 'string',
            isRequired: true,
            storageSystemTypeId: localTypeEnum.id,
          },
        ],
      });
      console.log('', chalk.green.bold('✓'), 'Initialize data table: StorageSystemConfigField');
    }
    // 三、初始化文件存储系统实例
    const defaultStorageSystem = await prisma.storageSystem.findFirst({
      where: {
        name: 'default',
      },
    });
    if (!defaultStorageSystem) {
      const localTypeEnum = await prisma.storageSystemTypeEnum.findFirst({
        where: {
          name: 'local',
        },
      });
      if (localTypeEnum) {
        await prisma.storageSystem.create({
          data: {
            name: 'default',
            typeId: localTypeEnum.id,
            description: '默认的系统存储实例',
            isPublic: true,
            config: {
              basePath: '%OS_HOME_DIR%/.nebulae/data/images',
              cachePath: '%OS_CACHE_DIR%/nebulae/images',
            },
          },
        });
      }
      console.log('', chalk.green.bold('✓'), 'Initialize data table: StorageSystem');
    }
    // 四、初始化标签
    const defaultTag = await prisma.tag.findFirst();
    if (!defaultTag) {
      await prisma.tag.createMany({
        data: [
          {
            name: '风景',
          },
          {
            name: '背景',
          },
          {
            name: '人物',
          },
          {
            name: '动物',
          },
          {
            name: '植物',
          },
          {
            name: '建筑',
          },
          {
            name: '交通工具',
          },
          {
            name: '食物',
          },
          {
            name: '图标',
          },
          {
            name: '插画',
          },
          {
            name: '艺术',
          },
          {
            name: '科技',
          },
          {
            name: '抽象',
          },
        ],
      });
      console.log('', chalk.green.bold('✓'), 'Initialize data table: Tag');
    }
    // 五、初始化用户：超级管理员
    const defaultAdmin = await prisma.user.findFirst({
      where: {
        role: 'admin',
      },
    });
    if (!defaultAdmin) {
      if (!process.env.ADMIN_EMAIL || !process.env.ADMIN_PASSWORD) {
        throw new Error('请在 .env 文件中设置 ADMIN_EMAIL 和 ADMIN_PASSWORD');
      }
      const hashedPassword = await bcrypt.hash(process.env.ADMIN_PASSWORD, 10);
      await prisma.user.create({
        data: {
          name: '管理员',
          email: process.env.ADMIN_EMAIL,
          password: hashedPassword,
          role: 'admin',
          isVerified: true,
        },
      });
      console.log('', chalk.green.bold('✓'), 'Initialize data table: User(admin)');
    }
  } catch (error) {
    console.error('执行种子数据脚本失败：', error);
  } finally {
    await prisma.$disconnect();
  }
}
